package com.example.administrator.reader.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.example.administrator.reader.R;
import com.example.administrator.reader.core.BaseActivity;
import com.example.administrator.reader.entity.RequestStatus;
import com.example.administrator.reader.request.BaseRequest;
import com.example.administrator.reader.request.UserRequest;
import com.example.administrator.reader.utils.Constants;
import com.example.administrator.reader.utils.MyToast;

public class LoginActivity extends BaseActivity {

    private Button bt_login;
    private EditText et_account;
    private EditText et_password;
    private UserRequest loginRequest;

    @Override
    protected void setUpContentView() {
        setContentView(R.layout.activity_login, R.string.login, R.menu.menu_register, MODE_BACK);
    }

    @Override
    protected void setUpView() {
        et_account = (EditText) findViewById(R.id.et_account);
        et_password = (EditText) findViewById(R.id.et_password);
        bt_login = (Button) findViewById(R.id.bt_login);

    }

    @Override
    protected void setUpData(Bundle savedInstanceState) {
        // 登录
        bt_login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String account = et_account.getText().toString();
                String password = et_password.getText().toString();
                loginRequest.refreshLoad(Constants.getLoginStatusUrl(account, password));
            }
        });

        loginRequest = new UserRequest();
        loginRequest.setInter(new BaseRequest.BaseInter<RequestStatus>() {
            @Override
            public void handleData(RequestStatus data) {

                if (data.getStatus().equals("success")){
                    MyToast.showToast("登录成功");
                    Intent intent = new Intent();


                    intent.putExtra("account", et_account.getText().toString());
                    setResult(Constants.resultCode, intent);
                    finish();
                }else {
                    MyToast.showToast("账号或密码错误");
                }

            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == resultCode){
            setResult(Constants.resultCode, data);
            finish();
        }
    }

    @Override
    public boolean onMenuItemClick(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.menu_register:
                startActivityForResult(new Intent(LoginActivity.this, RegisterActivity.class), Constants.requestCode);
                break;
        }
        return true;
    }


}
